/**
  ******************************************************************************
  * @file    usart.c
  * @brief   This file provides code for the configuration
  *          of the USART instances.
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "usart.h"
#include "string.h"
#include "i2c.h"
#include "stdio.h"

/* USER CODE BEGIN 0 */
#define HUART1_BUFF_SIZE 127
uint8_t huart1_Buff_Rcv[HUART1_BUFF_SIZE];
uint16_t huart1_Buff_Len = 0;
uint8_t huart1_Buff_Snd[HUART1_BUFF_SIZE];
char huart1_Buff_Print[HUART1_BUFF_SIZE];
/* USER CODE END 0 */

UART_HandleTypeDef huart1;
DMA_HandleTypeDef hdma_usart1_tx;
DMA_HandleTypeDef hdma_usart1_rx;

/* USART1 init function */

void MX_USART1_UART_Init(void)
{

  /* USER CODE BEGIN USART1_Init 0 */

  /* USER CODE END USART1_Init 0 */

  /* USER CODE BEGIN USART1_Init 1 */

  /* USER CODE END USART1_Init 1 */
  huart1.Instance = USART1;
  huart1.Init.BaudRate = 115200;
  huart1.Init.WordLength = UART_WORDLENGTH_8B;
  huart1.Init.StopBits = UART_STOPBITS_1;
  huart1.Init.Parity = UART_PARITY_NONE;
  huart1.Init.Mode = UART_MODE_TX_RX;
  huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart1.Init.OverSampling = UART_OVERSAMPLING_8;
  if (HAL_UART_Init(&huart1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART1_Init 2 */

  // Enable IDLE interrupt
  __HAL_UART_ENABLE_IT(&huart1, UART_IT_IDLE);
	
	// Enable DMA receive
	HAL_UART_Receive_DMA(&huart1, huart1_Buff_Rcv, HUART1_BUFF_SIZE);

  /* USER CODE END USART1_Init 2 */

}

void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle)
{

  GPIO_InitTypeDef GPIO_InitStruct = {0};
  if(uartHandle->Instance==USART1)
  {
  /* USER CODE BEGIN USART1_MspInit 0 */

  /* USER CODE END USART1_MspInit 0 */
    /* USART1 clock enable */
    __HAL_RCC_USART1_CLK_ENABLE();

    __HAL_RCC_GPIOA_CLK_ENABLE();
    /**USART1 GPIO Configuration
    PA9     ------> USART1_TX
    PA10     ------> USART1_RX
    */
    GPIO_InitStruct.Pin = GPIO_PIN_9|GPIO_PIN_10;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF7_USART1;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    /* USART1 DMA Init */
    /* USART1_TX Init */
    hdma_usart1_tx.Instance = DMA2_Stream7;
    hdma_usart1_tx.Init.Channel = DMA_CHANNEL_4;
    hdma_usart1_tx.Init.Direction = DMA_MEMORY_TO_PERIPH;
    hdma_usart1_tx.Init.PeriphInc = DMA_PINC_DISABLE;
    hdma_usart1_tx.Init.MemInc = DMA_MINC_ENABLE;
    hdma_usart1_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
    hdma_usart1_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
    hdma_usart1_tx.Init.Mode = DMA_NORMAL;
    hdma_usart1_tx.Init.Priority = DMA_PRIORITY_LOW;
    hdma_usart1_tx.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
    if (HAL_DMA_Init(&hdma_usart1_tx) != HAL_OK)
    {
      Error_Handler();
    }

    __HAL_LINKDMA(uartHandle,hdmatx,hdma_usart1_tx);

    /* USART1_RX Init */
    hdma_usart1_rx.Instance = DMA2_Stream2;
    hdma_usart1_rx.Init.Channel = DMA_CHANNEL_4;
    hdma_usart1_rx.Init.Direction = DMA_PERIPH_TO_MEMORY;
    hdma_usart1_rx.Init.PeriphInc = DMA_PINC_DISABLE;
    hdma_usart1_rx.Init.MemInc = DMA_MINC_ENABLE;
    hdma_usart1_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
    hdma_usart1_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
    hdma_usart1_rx.Init.Mode = DMA_NORMAL;
    hdma_usart1_rx.Init.Priority = DMA_PRIORITY_LOW;
    hdma_usart1_rx.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
    if (HAL_DMA_Init(&hdma_usart1_rx) != HAL_OK)
    {
      Error_Handler();
    }

    __HAL_LINKDMA(uartHandle,hdmarx,hdma_usart1_rx);

    /* USART1 interrupt Init */
    HAL_NVIC_SetPriority(USART1_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(USART1_IRQn);
  /* USER CODE BEGIN USART1_MspInit 1 */

  /* USER CODE END USART1_MspInit 1 */
  }
}

void HAL_UART_MspDeInit(UART_HandleTypeDef* uartHandle)
{

  if(uartHandle->Instance==USART1)
  {
  /* USER CODE BEGIN USART1_MspDeInit 0 */

  /* USER CODE END USART1_MspDeInit 0 */
    /* Peripheral clock disable */
    __HAL_RCC_USART1_CLK_DISABLE();

    /**USART1 GPIO Configuration
    PA9     ------> USART1_TX
    PA10     ------> USART1_RX
    */
    HAL_GPIO_DeInit(GPIOA, GPIO_PIN_9|GPIO_PIN_10);

    /* USART1 DMA DeInit */
    HAL_DMA_DeInit(uartHandle->hdmatx);
    HAL_DMA_DeInit(uartHandle->hdmarx);

    /* USART1 interrupt Deinit */
    HAL_NVIC_DisableIRQ(USART1_IRQn);
  /* USER CODE BEGIN USART1_MspDeInit 1 */

  /* USER CODE END USART1_MspDeInit 1 */
  }
}

/* USER CODE BEGIN 1 */
void USART_Process_Cmds()
{
	char buff[256];
	if( strcmp("ping\r\n",(char*)huart1_Buff_Snd) == 0 ){
		// i2c write
		Tool_Print("pong\r\n");
		return;
	}
	if( strcmp("i2c_write\r\n",(char*)huart1_Buff_Snd) == 0 ){
		// i2c write
		// Tool_I2C_Wrtie(0, 0x0123456787654321);
		Tool_Print("i2c write data: 0x0123456787654321\r\n");
		return;
	}
		if( strcmp("i2c_read\r\n",(char*)huart1_Buff_Snd) == 0 ){
		// i2c read
		uint64_t val = 0x01;
		Tool_I2C_Read(0, &val);
		//sprintf(buff,"i2c read data value: %lld\r\n",val);
			buff[0] = '_';
			buff[1] = '0' + ((uint8_t*)&val)[0];
			buff[2] = '0' + ((uint8_t*)&val)[1];
			buff[3] = '0' + ((uint8_t*)&val)[2];
			buff[4] = '0' + ((uint8_t*)&val)[3];
			buff[5] = '0' + ((uint8_t*)&val)[4];
			buff[6] = '0' + ((uint8_t*)&val)[5];
			buff[7] = '0' + ((uint8_t*)&val)[6];
			buff[8] = '0' + ((uint8_t*)&val)[7];
			buff[9] = '\r';
			buff[10] = '\n';
			buff[11] = 0;
		Tool_Print(buff);
		return;
	}
}

void Tool_Print(const char* str)
{
	strcpy(huart1_Buff_Print, str);
	HAL_UART_Transmit_DMA(&huart1, (uint8_t*)huart1_Buff_Print, strlen(str));
}

void USAR_UART_IDLECallback(UART_HandleTypeDef *huart)
{
		int nLen = 0;
		// Stop DMA
		HAL_UART_DMAStop(huart);
		// check dma data
		nLen = HUART1_BUFF_SIZE - __HAL_DMA_GET_COUNTER(huart->hdmarx);
		for(int i=0;i<nLen;i++){
			if(huart1_Buff_Len<HUART1_BUFF_SIZE){
				huart1_Buff_Snd[huart1_Buff_Len] = huart1_Buff_Rcv[i];
				huart1_Buff_Len += 1;
			}
			if( huart1_Buff_Rcv[i] == '\n' ){
				// call process function
				USART_Process_Cmds();
				// HAL_UART_Transmit_DMA(huart, huart1_Buff_Snd, huart1_Buff_Len);
				// reset buff len indicator
				huart1_Buff_Len = 0;
				break;
			}
		}
		// enable receive
		HAL_UART_Receive_DMA(huart, huart1_Buff_Rcv, HUART1_BUFF_SIZE);
}

void USER_UART_IRQHandler(UART_HandleTypeDef *huart)
{
    if(USART1 == huart->Instance)
    {
        if(RESET != __HAL_UART_GET_FLAG(&huart1, UART_FLAG_IDLE))
        {
            __HAL_UART_CLEAR_IDLEFLAG(&huart1);
            USAR_UART_IDLECallback(huart);
        }
    }
}

void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
	// enable receive
	HAL_UART_Receive_DMA(huart, huart1_Buff_Rcv, HUART1_BUFF_SIZE);
}

/* USER CODE END 1 */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
